﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace OnLineLogFileServer
{
    public partial class ShowOnLineClient : Form
    {
        public ShowOnLineClient()
        {
            InitializeComponent();
        }
        OnLineClient client = OnLineClient.Instance;
        private void ShowOnLineClient_Load(object sender, EventArgs e)
        {
            this.listView1.View = View.Details;
            this.listView1.Columns.Add("Address");
            this.listView1.Columns.Add("LastModify");

            this.FormClosing += ShowOnLineClient_FormClosing;
            client.NotifyChange += client_NotifyChange;
            client.HasUpdate = true;
        }

        void client_NotifyChange(Dictionary<string, OnLineClient.Entry> obj)
        {
            this.Invoke(new Action(() =>
            {
                this.Text = obj.Count.ToString();
                this.listView1.Items.Clear();
                this.listView1.Items.AddRange(
                    obj
                    .Select(p => p.Value)
                    .OrderByDescending(p => p.Address.Address.ToString())
                    .Select(p =>
                    {
                        var item = new ListViewItem(p.Address.ToString());
                        //item.SubItems.Add(p.Value.Address.ToString());
                        item.SubItems.Add(p.LastModifyDate.ToString("HH:mm:ss"));
                        item.Tag = p.Address;
                        return item;
                    }).ToArray()
                );
            }));
        }

        void ShowOnLineClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            client.HasUpdate = false;
            client.Clear();
            client.NotifyChange -= client_NotifyChange;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OnLineServer.ClearChaceFile(
                this.listView1.Items
                    .Cast<ListViewItem>()
                    .Select(p => p.Tag)
                    .Cast<IPEndPoint>()
            );
        }
    }
}
